// Fill out your copyright notice in the Description page of Project Settings.

#include "WorldRefLineBuilder.h"
#include "iterators/WorldHermiteIterator.h"

FWorldRefLineBuilder::FWorldRefLineBuilder(const FWorldRefLineGraph::Ptr& reflines,
											const FWorldEntityAxis& regionAxis,
											const glm::dmat4x4& parentMat)
	: _reflines(reflines)
	, _regionAxis(regionAxis)
	, _parentMat(parentMat)
{}

void FWorldRefLineBuilder::OnReset()
{
	_reflines->Clear();
}

void FWorldRefLineBuilder::OnRoad(const FWorldRoad::Ptr& road)
{
	// Cubic hermite spline.
	FWorldRefLineSpline::Ptr spline = std::make_shared<FWorldRefLineSpline>();

	// Go along the reference line and collect hermite spline intervals.
	FWorldHermiteIterator it(road->PlanView->Geometry, _regionAxis, road->Axis, _parentMat);
	for (; it.HasNext(); it.Next())
	{
		FWorldHermiteIterator::Interval step = it.GetInterval();
		spline->Add(step.Param, step.P0, step.M0, step.P1, step.M1);
	}

	// Update the S (distance) to t (param) lookup. Of course, the mapping from
	// distance to parameter is not linear. This is an approx.
	spline->UpdateReparam();

	// Commit
	_reflines->Add(road, spline);
}
